<template>
    <div>
        <a-tabs v-model="activeKey">
            <div slot="tabBarExtraContent">
                <a-button icon="plus" style="margin-right: 16px;" @click="showAddModal">
                    添加
                </a-button>
                <a-button icon="setting" @click="showManagementModal">
                    MQTT管理
                </a-button>
            </div>
            <a-tab-pane v-for="pane in panes" :key="pane.key">
                <span slot="tab">
                    <a-icon type="cloud-server" style="margin-right: 6px; font-size: 16px;" />
                    {{ pane.title }}
                    <a-popconfirm
                        v-if="panes.length > 1"
                        title="确定要删除这个配置吗?"
                        @confirm="() => remove(pane.key)"
                    >
                        <a-icon type="close" style="margin-left: 8px;" />
                    </a-popconfirm>
                </span>
                <mqtt-config
                    v-model="pane.config"
                    :db-id="pane.dbId"
                    :card-type-options="cardTypeOptions"
                    :server-type-options="serverTypeOptions"
                    :topic-type-options="topicTypeOptions"
                    :payload-format-options="payloadFormatOptions"
                    :ali-cloud-type-options="aliCloudTypeOptions"
                    @save="() => handleSaveConfig(pane)"
                    @saved="handleConfigSaved"
                />
            </a-tab-pane>
        </a-tabs>

        <a-modal
            title="MQTT网络管理"
            :visible="managementModalVisible"
            :footer="null"
            @cancel="handleModalCancel"
        >
            <a-button
                type="primary"
                style="margin-bottom: 16px;"
                @click="showAddModal"
            >
                添加新配置
            </a-button>
            <a-button
                type="primary"
                style="margin-bottom: 16px; margin-left: 8px;"
                icon="reload"
                :loading="loading"
                @click="handleRefresh"
            >
                刷新
            </a-button>
            <a-list bordered :data-source="panes">
                <a-list-item slot="renderItem" slot-scope="item">
                    <a-list-item-meta>
                        <span slot="title">{{ item.title }}</span>
                    </a-list-item-meta>
                    <template slot="actions">
                        <a @click="showRenameModal(item)">重命名</a>
                        <a-popconfirm
                            v-if="panes.length > 1"
                            title="确定要删除这个配置吗?"
                            @confirm="remove(item.key)"
                        >
                            <a>删除</a>
                        </a-popconfirm>
                    </template>
                </a-list-item>
            </a-list>
        </a-modal>

        <a-modal
            title="重命名"
            :visible="renameModalVisible"
            @ok="handleRename"
            @cancel="cancelRename"
        >
            <a-input
                v-model="newName"
                placeholder="请输入新的名称"
                @pressEnter="handleRename"
            />
        </a-modal>

        <a-modal
            title="添加新配置"
            :visible="addModalVisible"
            @ok="handleAddNewConfig"
            @cancel="handleAddCancel"
        >
            <a-input
                v-model="newConfigName"
                placeholder="请输入配置名称"
                @pressEnter="handleAddNewConfig"
            />
        </a-modal>
    </div>
</template>

<script>
import { Button, message } from 'ant-design-vue'
import MqttConfig from './MqttConfig.vue'
import { SettingsTabManager } from '@/api/TabManager'
import { getGatewayConfig } from '@/config/gateway-config'
import { mapGetters } from 'vuex'

export default {
    name: 'MqttNetworkSettings',
    components: {
        MqttConfig,
        'a-button': Button
    },
    data() {
        // const initialPanes = [
        //     {
        //         title: 'MQTT 1',
        //         config: this.createDefaultConfig(),
        //         key: '1',
        //         dbId: null,
        //         closable: false
        //     }
        // ]
        return {
            settingsTabManager: new SettingsTabManager(),
            // panes: initialPanes,
            // activeKey: initialPanes[0].key,
            panes: [], // 去掉默认(initialPanes创建无法保存)，另外一个函数his.panes.push(this.createDefaultPane())也会生成
            activeKey: '1',            
            newTabIndex: 1,
            managementModalVisible: false,
            renameModalVisible: false,
            paneToRename: null,
            newName: '',
            addModalVisible: false,
            newConfigName: '',
            dataLoaded: false,
            loading: false,
            timestamp: null, // 用于跟踪数据更新时间戳
            cardTypeOptions: [],
            serverTypeOptions: [],
            topicTypeOptions: [],
            payloadFormatOptions: [],
            aliCloudTypeOptions: []
        }
    },
    computed: {
        ...mapGetters('groupTree', ['selectedDeviceInfo'])
    },       
    mounted() {
        console.log('🚀 [MqttNetworkSettings] 组件 mounted')
        this.loadMqttSelectConfig()
    }, 
    methods: {
        createTopics(count) {
            return Array.from({ length: count }, (_, i) => ({
                id: i + 1,
                topic: `Topic${i + 1}`,
                content: '',
                qos: 'Qos0',
                enabled: false,
                payloadFormat: '',
                interval: 30,
                topicType: ''
            }))
        },

        // 创建默认配置
        createDefaultConfig() {
            return {
                name: 'name',
                address: '127.0.0.1',
                port: '1883',
                clientId: 'clientId',
                username: 'userName',
                password: 'password',
                keepalive: 60,
                cardType: '5000',
                serverType: '1001',
                publishTopics: this.createTopics(5),
                subscribeTopics: this.createTopics(5),
                securityLayer: 'null',
                clearSession: false,
                startTls: true
            }
        },

        async loadMqttSelectConfig() {
            try {
                const res = await this.settingsTabManager.getMqttUIConfig()
                console.log('🔍 [MqttNetworkSettings] 加载MQTT配置UI选项原始响应:', res)
                
                if (res.data && res.code === 0) {
                    console.log('🔍 [MqttNetworkSettings] 解析前的数据:', res.data)
                    const data = JSON.parse(res.data)
                    console.log('🔍 [MqttNetworkSettings] 解析后的数据结构:', data)
                    
                    // 确保数据格式正确，提供默认值
                    this.cardTypeOptions = data.NetworkCard
                    this.serverTypeOptions = data.ServerType 
                    this.topicTypeOptions = data.Topic
                    this.payloadFormatOptions = data.Payload
                    this.aliCloudTypeOptions = data.AliCloudType

                    // 继续获取自定义主题列表
                    const resCustomTopic = await this.settingsTabManager.getMqttCustomTopicList()
                    if (resCustomTopic.data && resCustomTopic.code === 0) {
                        const customTopicList = JSON.parse(resCustomTopic.data)
                        for (const item of customTopicList) {
                            this.payloadFormatOptions.push(item)
                        }
                    }

                } else {
                    console.warn('⚠️ [MqttNetworkSettings] 响应格式不正确，使用默认选项')
                    this.setDefaultOptions()
                }
            } catch (error) {
                console.error('❌ [MqttNetworkSettings] 加载MQTT配置UI选项失败:', error)
                message.error('加载MQTT配置UI选项失败: ' + (error.message || '未知错误'))
                this.setDefaultOptions()
            }
        },
        
        // 设置默认选项
        setDefaultOptions() {
            this.cardTypeOptions = []
            this.serverTypeOptions = []
            this.topicTypeOptions = []
            this.payloadFormatOptions = []
            this.aliCloudTypeOptions = []
            console.log('✅ [MqttNetworkSettings] 已设置默认选项')
        },

        // 添加新配置
        async add(title) {
            // 需要根据GATEWAY_CONFIGS中的硬件信息(mqttCount)，来限制添加MQTT配置的数量
            // 根据设备类型获取updateMode
            const deviceType = this.selectedDeviceInfo.gatewayType || this.selectedDeviceInfo.deviceType
            const gatewayConfig = getGatewayConfig(deviceType)
            const mqttCount = gatewayConfig.hardwareInfo.mqttCount
            if (this.panes.length >= mqttCount) {
                this.$message.error('MQTT配置数量已达到最大限制' + mqttCount)
                return
            }
            try {
                this.loading = true

                const newConfig = {
                    name: title,
                    dbId: 0,
                    groupDeviceId: 0,
                    config: {
                        id: 0,
                        name: title,
                        address: '127.0.0.1',
                        port: '1883',
                        clientId: `clientId_${Date.now()}`,
                        username: 'userName',
                        password: 'password',
                        keepalive: 60,
                        cardType: '5000',
                        serverType: '1001',
                        publishTopics: this.createTopics(5),
                        subscribeTopics: this.createTopics(5),
                        securityLayer: 'null',
                        clearSession: false,
                        startTls: true
                    }
                }

                console.log('➕ [MqttNetworkSettings] 添加MQTT配置:', newConfig)
                // 调用API添加配置
                const res = await this.settingsTabManager.addMqttConfig(JSON.stringify(newConfig))
                if (res.data && res.code === 0) {
                    // 生成新的activeKey
                    const activeKey = `${this.newTabIndex + 1}`
     
                    this.panes.push({
                        title: title,
                        config: newConfig.config,
                        key: activeKey,
                        dbId: res.data, // 保存数据库id
                        closable: true
                    })
                    this.activeKey = activeKey
                    this.newTabIndex++

                    message.success('MQTT配置添加成功')
                } else {
                    throw new Error('添加配置返回数据格式错误')
                }
            } catch (error) {
                console.error('❌ [MqttNetworkSettings] 添加MQTT配置失败:', error)
                message.error('添加配置失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading = false
            }
        },

        // 删除配置
        async remove(targetKey) {
            if (this.panes.length === 1) {
                message.warning('这是最后一个配置，无法删除')
                return
            }

            try {
                this.loading = true

                const targetPane = this.panes.find(pane => pane.key === targetKey)
                if (!targetPane) {
                    throw new Error('未找到要删除的配置')
                }

                console.log('🗑️ [MqttNetworkSettings] 删除MQTT配置:', targetPane)

                // 调用API删除配置，使用数据库id
                const response = await this.settingsTabManager.deleteMqttConfig(targetPane.dbId)

                // 判断删除是否成功
                if (!response || response.code !== 0) {
                    throw new Error(response?.message || '删除失败，请重试')
                }

                // 删除成功后，更新本地面板
                let activeKey = this.activeKey
                let lastIndex
                this.panes.forEach((pane, i) => {
                    if (pane.key === targetKey) {
                        lastIndex = i - 1
                    }
                })

                const panes = this.panes.filter(pane => pane.key !== targetKey)
                if (panes.length && activeKey === targetKey) {
                    if (lastIndex >= 0) {
                        activeKey = panes[lastIndex].key
                    } else {
                        activeKey = panes[0].key
                    }
                }

                this.panes = panes
                this.activeKey = activeKey

                message.success('MQTT配置删除成功')
            } catch (error) {
                console.error('❌ [MqttNetworkSettings] 删除MQTT配置失败:', error)
                message.error('删除配置失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading = false
            }
        },

        // 重命名配置
        async handleRename() {
            if (this.newName && this.paneToRename) {
                try {
                    this.loading = true

                    // 创建新的配置对象以触发响应式更新
                    const updatedConfig = { ...this.paneToRename.config, name: this.newName }
                    const configData = {
                        id: this.paneToRename.dbId,
                        name: this.newName,
                        groupDeviceId: this.paneToRename.groupDeviceId,
                        config: updatedConfig
                    }

                    console.log(
                        '✏️ [MqttNetworkSettings] 重命名MQTT配置:',
                        this.paneToRename.dbId,
                        this.newName
                    )

                    // 调用API更新配置，使用数据库id
                    const res = await this.settingsTabManager.updateMqttConfig(
                        this.paneToRename.dbId,
                        JSON.stringify(configData)
                    )
                    if (res.code !== 0) {
                        throw new Error(res?.msg || '重命名失败，请重试')
                    }

                    // 更新本地数据 - 使用新对象以确保响应式更新
                    this.paneToRename.title = this.newName
                    this.paneToRename.config = updatedConfig

                    message.success('配置重命名成功')
                } catch (error) {
                    console.error('❌ [MqttNetworkSettings] 重命名MQTT配置失败:', error)
                    message.error('重命名失败: ' + (error.message || '未知错误'))
                } finally {
                    this.loading = false
                }
            }
            this.cancelRename()
        },

        // 复制配置
        async copyConfig(sourceKey) {
            try {
                this.loading = true

                const sourcePane = this.panes.find(p => p.key === sourceKey)
                if (!sourcePane) {
                    throw new Error('未找到要复制的配置')
                }

                const newTitle = `${sourcePane.title} - 副本`

                console.log(
                    '📋 [MqttNetworkSettings] 复制MQTT配置:',
                    sourcePane.dbId,
                    newTitle
                )

                // 调用API复制配置，使用数据库id
                const response = await this.settingsTabManager.copyMqttConfig(
                    sourcePane.dbId,
                    newTitle
                )
                console.log('🔄 [MqttNetworkSettings] 复制MQTT配置:', response)
            } catch (error) {
                console.error('❌ [MqttNetworkSettings] 复制MQTT配置失败:', error)
                message.error('复制配置失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading = false
            }
        },

        // 重置配置
        async resetConfig(configKey) {
            try {
                this.loading = true

                const targetPane = this.panes.find(p => p.key === configKey)
                if (!targetPane) {
                    throw new Error('未找到要重置的配置')
                }

                console.log('🔄 [MqttNetworkSettings] 重置MQTT配置:', targetPane.dbId)

                // 调用API重置配置，使用数据库id
                await this.settingsTabManager.resetMqttConfig(targetPane.dbId)

                // 重新加载配置列表
                await this.loadMqttConfigs()

                message.success('配置重置成功')
            } catch (error) {
                console.error('❌ [MqttNetworkSettings] 重置MQTT配置失败:', error)
                message.error('重置配置失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading = false
            }
        },

        // 处理单个配置保存成功
        handleConfigSaved(config) {
            console.log('✅ [MqttNetworkSettings] MQTT配置保存成功:', config)
            // 可以在这里处理其他后续操作，比如更新状态等
        },

        // 保存单个MQTT配置
        async handleSaveConfig(pane) {
            if (this.loading) return
            
            try {
                this.loading = true
                const configData = {
                    config: pane.config,
                    id: pane.dbId
                }

                console.log(
                    '💾 [MqttNetworkSettings] 保存MQTT配置:',
                    pane.dbId,
                    configData
                )

                // 调用API保存配置
                const response = await this.settingsTabManager.updateMqttConfig(
                    pane.dbId,
                    JSON.stringify(configData)
                )

                // 判断保存是否成功
                if (!response || response.code !== 0) {
                    throw new Error(response?.msg || '保存失败，请重试')
                }

                message.success('MQTT配置保存成功')

                // 发送更新事件给父组件
                const updateTimestamp = new Date().getTime()
                this.$emit('settings-updated', {
                    mqttNetworkSettings: {
                        code: 0,
                        data: JSON.stringify(this.panes.map(pane => ({
                            id: pane.dbId,
                            name: pane.title,
                            config: pane.config
                        }))),
                        timestamp: updateTimestamp
                    }
                })

                // 更新本地时间戳，避免重复更新
                this.timestamp = updateTimestamp

                // 可以在这里添加其他后续操作
                this.handleConfigSaved(pane.config)
            } catch (error) {
                console.error('❌ [MqttNetworkSettings] 保存MQTT配置失败:', error)
                message.error('保存失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading = false
            }
        },

        // 更新数据的方法，供父组件调用 - 优化版
        updateData(settingsData) {
            console.log('🔄 [MqttNetworkSettings] 更新数据:', settingsData)

            // 如果传入null，执行强制重置操作
            if (settingsData === null) {
                console.log('🔄 [MqttNetworkSettings] 执行强制重置操作')
                this.panes = []
                this.activeKey = '1'
                this.newTabIndex = 1
                this.dataLoaded = false
                this.timestamp = null
                console.log('✅ [MqttNetworkSettings] 强制重置完成')
                return
            }

            if (!settingsData) {
                console.log('⚠️ [MqttNetworkSettings] 没有有效数据，跳过更新')
                return
            }

            try {
                // 检查时间戳，避免重复更新
                if (settingsData.timestamp && this.timestamp === settingsData.timestamp) {
                    console.log('⚠️ [MqttNetworkSettings] 时间戳相同，跳过重复更新:', settingsData.timestamp)
                    return
                }

                if (settingsData.code === 0) {
                    const parsedData = JSON.parse(settingsData.data)
                    console.log('🔍 [MqttNetworkSettings] 解析后的数据:', parsedData)

                    // 确保是数组
                    if (!Array.isArray(parsedData)) {
                        console.log('⚠️ [MqttNetworkSettings] 数据不是数组格式，跳过更新')
                        return
                    }

                    // 清空现有面板并重新创建，避免复杂的合并操作
                    this.panes = []
                    console.log('🔄 [MqttNetworkSettings] 已清空现有面板')

                    // 逐个创建新面板
                    parsedData.forEach((config, index) => {
                        const newPane = {
                            title: config.config.name,
                            config: this.createConfigFromData(config.config),
                            key: `${index + 1}`, // 使用序号作为key
                            dbId: config.id, // 保存数据库id
                            closable: index > 0 // 第一个面板不能关闭
                        }
                        console.log('🔄 [MqttNetworkSettings] 创建新面板 config.name:', config.name, newPane)
                        this.panes.push(newPane)
                    })   
                    
                    // 确保至少有一个面板
                    if (this.panes.length === 0) {
                        console.log('⚠️ [MqttNetworkSettings] 没有数据，创建默认面板')
                        // this.panes.push(this.createDefaultPane())
                    }

                    // 设置活动面板
                    if (this.panes.length > 0) {
                        this.activeKey = this.panes[0].key
                        this.newTabIndex = this.panes.length
                    }

                    // 更新时间戳
                    this.timestamp = settingsData.timestamp
                    this.dataLoaded = true
                    console.log('✅ [MqttNetworkSettings] 数据更新成功，时间戳:', this.timestamp)                    
                } else {
                    console.log('⚠️ [MqttNetworkSettings] 数据更新失败', settingsData)
                    message.error('数据更新失败: ' + (settingsData?.msg || '未知错误'))
                }
            } catch (error) {
                console.error('❌ [MqttNetworkSettings] 数据更新失败:', error)
            }
        },

        // 从数据创建配置，避免深度合并
        createConfigFromData(configData) {
            if (!configData) return this.createDefaultConfig()

            return {
                name: configData.name || 'name',
                address: configData.address || '127.0.0.1',
                port: configData.port || '1883',
                clientId: configData.clientId || 'clientId',
                username: configData.username || 'userName',
                password: configData.password || 'password',
                keepalive: configData.keepalive || 60,
                cardType: configData.cardType || '',
                serverType: configData.serverType || '',
                publishTopics: this.createTopicsFromData(configData.publishTopics, 5),
                subscribeTopics: this.createTopicsFromData(configData.subscribeTopics, 5),
                securityLayer: configData.securityLayer || 'null',
                clearSession: configData.clearSession || false,
                startTls: configData.startTls || true,
                sslFileType: configData.sslFileType || 'CAFile',
                cafile: configData.cafile || '',
                certfile: configData.certfile || '',
                keyfile: configData.keyfile || ''                
            }
        },

        // 从数据创建主题数组
        createTopicsFromData(topicsData, defaultCount) {
            if (Array.isArray(topicsData) && topicsData.length > 0) {
                return topicsData.map((topic, index) => ({
                    id: topic.id || index + 1,
                    topic: topic.topic || `Topic${index + 1}`,
                    content: topic.content || '',
                    qos: topic.qos || 'Qos0',
                    enabled: topic.enabled || false,
                    payloadFormat: topic.payloadFormat || '',
                    interval: topic.interval || 30,
                    topicType: topic.topicType || ''
                }))
            }
            return this.createTopics(defaultCount)
        },

        // 创建默认面板
        createDefaultPane() {
            return {
                title: 'MQTT 1',
                config: this.createDefaultConfig(),
                key: '1',
                dbId: null, // 默认面板没有数据库id
                closable: false
            }
        },

        // 获取当前配置数据
        getCurrentConfig() {
            return this.panes.map(pane => ({
                id: pane.dbId, // 使用数据库id
                title: pane.title,
                config: pane.config
            }))
        },

        // === 界面交互方法 ===
        showManagementModal() {
            this.managementModalVisible = true
        },
        handleModalCancel() {
            this.managementModalVisible = false
        },
        showRenameModal(pane) {
            this.paneToRename = pane
            this.newName = pane.title
            this.renameModalVisible = true
        },
        // 添加刷新方法
        async handleRefresh() {
            try {
                this.loading = true
                await this.loadMqttSelectConfig()
                message.success('配置信息刷新成功')
            } catch (error) {
                console.error('❌ [MqttNetworkSettings] 刷新配置失败:', error)
                message.error('刷新失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading = false
            }
        },
        cancelRename() {
            this.renameModalVisible = false
            this.paneToRename = null
            this.newName = ''
        },
        showAddModal() {
            this.newConfigName = `MQTT ${this.panes.length + 1}`
            this.addModalVisible = true
        },
        handleAddCancel() {
            this.addModalVisible = false
        },
        handleAddNewConfig() {
            if (!this.newConfigName) {
                message.error('配置名称不能为空')
                return
            }
            this.add(this.newConfigName)
            this.addModalVisible = false
        }
    }
}
</script>

<style scoped>
.ant-form-item {
    margin-bottom: 0;
}
</style>